package cn.tedu.smartos.volunteer.Service.impl;

import cn.tedu.smartos.activity.pojo.vo.ActivityVO;
import cn.tedu.smartos.base.exception.ServiceException;
import cn.tedu.smartos.base.response.JsonResult;
import cn.tedu.smartos.base.response.StatusCode;
import cn.tedu.smartos.baseuser.pojo.entity.User;
import cn.tedu.smartos.baseuser.pojo.vo.UserVO;
import cn.tedu.smartos.volunteer.Service.VolunteerService;
import cn.tedu.smartos.volunteer.mapper.VolunteerMapper;
import cn.tedu.smartos.volunteer.pojo.dto.ActivityQueryParam;
import cn.tedu.smartos.volunteer.pojo.dto.PasswordUpdateParam;
import cn.tedu.smartos.volunteer.pojo.dto.UserUpdateParam;
import cn.tedu.smartos.volunteer.pojo.entity.PointsExchange;
import cn.tedu.smartos.volunteer.pojo.entity.PointsGoods;
import cn.tedu.smartos.volunteer.pojo.vo.VolunteerInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class VolunteerServiceImpl implements VolunteerService {

    @Autowired
    private VolunteerMapper volunteerMapper;

    @Override
    public UserVO getUserInfo(String username) {
        User user = volunteerMapper.selectUserByUsername(username);
        if (user == null) {
            throw new ServiceException(StatusCode.USER_NOT_EXIT);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);

        // 修正URL：去掉重复的 "/avatar"
        if (user.getAvatarUrl() != null) {
            String filename = user.getAvatarUrl().replace("/avatar/", ""); // 移除多余路径
            userVO.setAvatarUrl("http://localhost:8080/avatar/" + filename);
        }

        return userVO;
    }

    @Override
    public JsonResult updateUserInfo(UserUpdateParam param) {
        User user = new User();
        BeanUtils.copyProperties(param, user);
        int rows = volunteerMapper.updateUser(user);
        if (rows == 0) {
            throw new ServiceException(StatusCode.FAILED, "更新用户信息失败");
        }
        return JsonResult.ok();
    }

    @Override
    public JsonResult updatePassword(PasswordUpdateParam param) {
        User user = volunteerMapper.selectUserByUsername(param.getUsername());
        if (user == null) {
            throw new ServiceException(StatusCode.USER_NOT_EXIT, "用户不存在");
        }
        if (!user.getPassword().equals(param.getOldPassword())) {
            throw new ServiceException(StatusCode.FAILED, "旧密码不正确");
        }
        if (param.getOldPassword().equals(param.getNewPassword())) {
            throw new ServiceException(StatusCode.FAILED, "新密码不能与旧密码相同");
        }

        int rows = volunteerMapper.updatePassword(param.getUsername(), param.getNewPassword());
        if (rows == 0) {
            throw new ServiceException(StatusCode.FAILED, "更新密码失败");
        }
        return JsonResult.ok("密码修改成功");
    }

    @Override
    public VolunteerInfoVO getVolunteerInfo(String username) {
        User user = volunteerMapper.selectUserByUsername(username);
        if (user == null) {
            throw new ServiceException(StatusCode.USER_NOT_EXIT);
        }

        VolunteerInfoVO volunteerInfo = volunteerMapper.selectVolunteerInfoByUserId(user.getUserId());
        if (volunteerInfo == null) {
            throw new ServiceException(StatusCode.FAILED, "用户不是志愿者");
        }

        // 获取当前积分
        Integer currentPoints = volunteerMapper.selectCurrentPointsByUserId(user.getUserId());
        if (currentPoints != null) {
            volunteerInfo.setTotalPoints(currentPoints);
        } else {
            volunteerInfo.setTotalPoints(0);
        }

        return volunteerInfo;
    }

//    @Override
//    public List<ActivityVO> getMyActivities(String username) {
//        User user = volunteerMapper.selectUserByUsername(username);
//        if (user == null) {
//            throw new ServiceException(StatusCode.USER_NOT_EXIT);
//        }
//        VolunteerInfoVO volunteerInfo = volunteerMapper.selectVolunteerInfoByUserId(user.getUserId());
//        if (volunteerInfo == null) {
//            throw new ServiceException(StatusCode.FAILED, "用户不是志愿者");
//        }
//
//        // 查询志愿者参与的所有活动
//        List<ActivityVO> activities = volunteerMapper.selectActivitiesByVolunteerId(volunteerInfo.getVolunteerId());
//
//        // 查询志愿者已签到的活动
//        List<Long> checkedInActivities = volunteerMapper.selectCheckedInActivities(user.getUserId());
//
//        // 标记已完成的活动
//        activities.forEach(activity -> {
//            if (checkedInActivities.contains(activity.getActivityId()) ||
//                    "已结束".equals(activity.getStatus())) {
//                activity.setStatus(Integer.valueOf("已完成"));
//            }
//        });
//
//        return activities;
//    }

//    @Override
//    public List<ActivityVO> getAllActivities(ActivityQueryParam param) {
//        return volunteerMapper.selectAllActivities(param);
//    }

//    @Override
//    public JsonResult joinActivity(String username, Long activityId) {
//        User user = volunteerMapper.selectUserByUsername(username);
//        if (user == null) {
//            throw new ServiceException(StatusCode.USER_NOT_EXIT);
//        }
//
//        // 检查活动是否可报名
//        ActivityVO activity = volunteerMapper.selectActivityById(activityId);
//        if (activity == null) {
//            throw new ServiceException(StatusCode.FAILED, "活动不存在");
//        }
//
//        if (activity.getMaxParticipants() != null &&
//                activity.getCurrentParticipants() != null &&
//                activity.getCurrentParticipants() >= activity.getMaxParticipants()) {
//            throw new ServiceException(StatusCode.FAILED, "活动人数已满");
//        }
//
//        // 检查是否已报名
//        Integer count = volunteerMapper.countActivityParticipation(activityId, user.getUserId());
//        if (count > 0) {
//            throw new ServiceException(StatusCode.FAILED, "您已报名该活动");
//        }
//
//        // 报名活动
//        int rows = volunteerMapper.insertActivityParticipation(activityId, user.getUserId());
//        if (rows == 0) {
//            throw new ServiceException(StatusCode.FAILED, "参加活动失败");
//        }
//
//        // 更新参与人数
//        volunteerMapper.incrementActivityParticipants(activityId);
//
//        return JsonResult.ok();
//    }

    @Override
    public List<PointsGoods> getAllPointsGoods() {
        return volunteerMapper.selectAllPointsGoods();
    }

    @Override
    @Transactional
    public JsonResult exchangePointsGoods(String username, Long goodsId, Integer quantity) {
        User user = volunteerMapper.selectUserByUsername(username);
        if (user == null) {
            throw new ServiceException(StatusCode.USER_NOT_EXIT);
        }

        VolunteerInfoVO volunteerInfo = volunteerMapper.selectVolunteerInfoByUserId(user.getUserId());
        if (volunteerInfo == null) {
            throw new ServiceException(StatusCode.FAILED, "用户不是志愿者");
        }

        // 获取当前积分
        Integer currentPoints = volunteerMapper.selectCurrentPointsByUserId(user.getUserId());
        if (currentPoints == null) {
            currentPoints = 0;
        }

        PointsGoods goods = volunteerMapper.selectAllPointsGoods().stream()
                .filter(g -> g.getGoodsId().equals(goodsId))
                .findFirst()
                .orElseThrow(() -> new ServiceException(StatusCode.FAILED, "商品不存在"));

        int requiredPoints = goods.getPointsRequired() * quantity;
        if (currentPoints < requiredPoints) {
            throw new ServiceException(StatusCode.FAILED, "积分不足");
        }

        PointsExchange exchange = new PointsExchange();
        exchange.setUserId(user.getUserId());
        exchange.setGoodsId(goodsId);
        exchange.setQuantity(quantity);
        exchange.setPointsCost(requiredPoints);
        exchange.setStatus(0);

        int rows = volunteerMapper.insertPointsExchange(exchange);
        if (rows == 0) {
            throw new ServiceException(StatusCode.FAILED, "兑换失败");
        }

        // 更新积分记录
        rows = volunteerMapper.updateVolunteerPoints1(user.getUserId(), currentPoints - requiredPoints);
        if (rows == 0) {
            throw new ServiceException(StatusCode.FAILED, "更新积分失败");
        }

        return JsonResult.ok();
    }

    @Override
    public List<PointsExchange> getMyPointsExchanges(String username) {
        User user = volunteerMapper.selectUserByUsername(username);
        if (user == null) {
            throw new ServiceException(StatusCode.USER_NOT_EXIT);
        }
        return volunteerMapper.selectPointsExchangesByUserId(user.getUserId());
    }
}